package com.guomao.service;

import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

import com.guomao.entity.User;

@Service
public class UserService {
    private final List<User> users = new ArrayList<>();
    private final AtomicLong counter = new AtomicLong();

    public UserService() {
        // 初始化一些测试数据
        users.add(new User(counter.incrementAndGet(), "张三", "zhangsan@guomao.com"));
        users.add(new User(counter.incrementAndGet(), "李四", "lisi@guomao.com"));
    }

    public List<User> getAllUsers() {
        return new ArrayList<>(users);
    }

    public User getUserById(Long id) {
        return users.stream().filter(user -> user.getId().equals(id)).findFirst().orElse(null);
    }

    public User createUser(User user) {
        user.setId(counter.incrementAndGet());
        users.add(user);
        return user;
    }

    public User updateUser(Long id, User user) {
        for (User u : users) {
            if (u.getId().equals(id)) {
                u.setName(user.getName());
                u.setEmail(user.getEmail());
                return u;
            }
        }
        return null;
    }

    public boolean deleteUser(Long id) {
        return users.removeIf(user -> user.getId().equals(id));
    }
}